import { controller, httpGet, httpPost } from "inversify-express-utils";
import { Request, Response } from "express";
import { inject } from "inversify";
import { UserService } from "./service";
import Result from "../../utils/Result";
import { JWT } from "../../utils/jwt";

@controller("/user")
export class UserController {
  constructor(
    // 注入UserService
    @inject(UserService) private readonly userService: UserService,
    // 注入JWT
    @inject(JWT) private readonly jwt: JWT
  ) {}

  /**
   * 获取用户列表
   * 注解接收第二个参数，第二个参数是中间件，在需要验证token的地方使用
   * /user/findList
   */
  @httpGet("/findList", JWT.middleware())
  public async findList(req: Request, res: Response) {
    // 设置了JWT中间件后，req中会包含用户信息
    console.log(req.user);

    let result = await this.userService.findList();
    res.json(Result.ok(result));
  }

  /**
   * 获取用户详情
   * /user/findDetail
   */
  @httpGet("/find/:id")
  public async findById(req: Request, res: Response) {
    let result = await this.userService.findById(parseInt(req.params.id));
    res.json(Result.ok(result));
  }

  /**
   * 创建用户
   * /user/create
   */
  @httpPost("/create")
  public async create(req: Request, res: Response) {
    let result = await this.userService.create(req.body);
    let token = this.jwt.createToken(result);
    res.json(
      Result.ok({
        result,
        token,
      })
    );
  }
}
